package com.imooc.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.NamedThreadLocal;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
public final class DynamicDataSourceContextHolder {

    /**
     * 双端队列其实本质就是一个栈
     */
    private static final ThreadLocal<Deque<String>> DATASOURCE_CONTEXT = NamedThreadLocal.
            withInitial(() -> new ArrayDeque<>());

    private DynamicDataSourceContextHolder() {
        if (DATASOURCE_CONTEXT != null) {
            throw new RuntimeException("禁止反射创建");
        }
    }

    public static String getCurrentDataSource() {
        //todo 2023-07-31 修复补丁。因为可能返回null，而ConcurrentHashMap的get方法不能传入null，否则报空指针
        String peek = DATASOURCE_CONTEXT.get().peek();
        return Objects.isNull(peek) ? "" : peek;
    }

    public static String addDataSource(String dds) {
        String datasource = StringUtils.isEmpty(dds) ? "" : dds;
        DATASOURCE_CONTEXT.get().push(datasource);
        return datasource;
    }

    public static void removeCurrentDataSource() {
        Deque<String> deque = DATASOURCE_CONTEXT.get();
        deque.poll();
        if (deque.isEmpty()) {
            DATASOURCE_CONTEXT.remove();
        }
    }

}
